package com.bridgeintelligent.tag.scene.service;

import com.bridgeintelligent.tag.remotefile.RemoteFileHandler;
import com.bridgeintelligent.tag.scene.api.IHelpService;
import com.bridgeintelligent.tag.scene.api.entity.HelpInfo;
import com.bridgeintelligent.tag.scene.mapper.HelpInfoMapper;
import com.bridgeintelligent.tag.user.mgmt.pojo.User;
import com.bridgeintelligent.tag.webserver.dim.mgmt.api.IdWorker;
import com.bridgeintelligent.tag.webserver.security.TagSecurityHelper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;

/**
 * @description
 * @author: grp 2021-03-29 14:28
 **/
@Service
@Slf4j
@AllArgsConstructor
public class HelpServiceImpl implements IHelpService {


    private HelpInfoMapper helpInfoMapper;
    private RemoteFileHandler remoteFileHandler;

    private final static String PATH_PRE_FORMAT = "/help/%s";

    @Override
    public void downLoad(HttpServletResponse response, HttpServletRequest request) {
        HelpInfo helpInfo = helpInfoMapper.findHelpInfo();
        if(helpInfo==null){
            response.setStatus(HttpStatus.NOT_FOUND.value());
            return;
        }
        File file = new File(helpInfo.getPath());
        if(!file.exists()){
            response.setStatus(HttpStatus.NOT_FOUND.value());
            return;
        }
        try(InputStream bis = new BufferedInputStream(new FileInputStream(file));
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream())) {
            createFileName(helpInfo, response, request);
            byte[] buffer = new byte[bis.available()];
            bis.read(buffer);
            outputStream.write(buffer);
            outputStream.flush();
            IOUtils.closeQuietly(outputStream);
            IOUtils.closeQuietly(bis);
        }catch (Exception e){
            log.error("获取图片失败",e);
        }
    }

    public void createFileName(HelpInfo helpInfo,HttpServletResponse response,
                               HttpServletRequest request) throws UnsupportedEncodingException {
        response.reset();
        String fileName = helpInfo.getName();
        boolean flag = request.getHeader("User-Agent")
                .indexOf("like Gecko") > 0;
        if (request.getHeader("User-Agent")
                .toLowerCase()
                .indexOf("msie") > 0 || flag) {
            fileName = URLEncoder.encode(fileName, "UTF-8");//IE浏览器
        } else {
            fileName = new String(fileName.replaceAll(" ", "")
                    .getBytes("UTF-8"), "ISO8859-1");
        }
        String date = DateFormatUtils.format(new Date(), "yyyy-MM-dd");
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName +"-"+
                date+"."+ helpInfo.getType());
        response.setContentType(helpInfo.getContentType());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String upload(MultipartFile file) {
        HelpInfo helpInfo = new HelpInfo();
        User user = TagSecurityHelper.currentUser();
        helpInfo.setCreateTime(new Date()).setCreatorId(user.getUserId()).setId(IdWorker.nextId())
                .setName(StringUtils.substringBeforeLast(file.getOriginalFilename(),"."))
                .setType(StringUtils.substringAfterLast(file.getOriginalFilename(),"."));
        String fileName = helpInfo.getId()+ "." +helpInfo.getType();
        String path = remoteFileHandler.writeByPath(file,
                remoteFileHandler.getPath(String.format(PATH_PRE_FORMAT,
                        DateFormatUtils.format(new Date(), DateFormatUtils.ISO_8601_EXTENDED_DATE_FORMAT.getPattern()
                        ))),fileName);
        helpInfo.setPath(path).setContentType(file.getContentType());
        helpInfoMapper.truncate();
        helpInfoMapper.insert(helpInfo);
        return path;
    }

    @Override
    public String getFileName() {
        HelpInfo helpInfo = helpInfoMapper.findHelpInfo();
        if(helpInfo==null){
            return null;
        }
        return helpInfo.getName()+"."+helpInfo.getType();
    }
}
